package com.burt.zookeeper.curator.queue;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * Description: 工具类
 * User: Burt
 * Date: 2017-08-22
 * Time: 9:37
 */
public class CommonHelper {

    /**
     * byte数组转object
     * @param bytes
     * @return
     */
    public static Object Byte2Object(byte[] bytes){
        Object object = null;
        ByteArrayInputStream bi = null;
        ObjectInputStream oi = null;

        try {
            bi = new ByteArrayInputStream(bytes);
            oi = new ObjectInputStream(bi);

            object = oi.readObject();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }finally {
            if (null != bi){
                try {
                    bi.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != oi){
                try {
                    oi.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return object;
    }

    /**
     * object转byte数组
     * @param object
     * @return
     */
    public static byte[] Object2Byte(Object object){

        byte[] bytes = null;
        ByteArrayOutputStream bo = null;
        ObjectOutputStream oo = null;

        try {
            bo = new ByteArrayOutputStream();
            oo = new ObjectOutputStream(bo);

            oo.writeObject(object);
            bytes = bo.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (null != bo){
                try {
                    bo.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != oo){
                try {
                    oo.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return bytes;
    }
}
